var app = angular.module("addApp", []),
	weixin_id = UI.getParameterByName('weixin_id');

var timeout_json = function(data, $window) {
	if(data.returnCode == 999994) {
		var ss = 3;
		layer.msg(data.returnMessage + "！<strong class='Ajax_Out'>" + ss + "</strong> 秒后前往登录页", 50, -1);
		var picInt = setInterval(function() {
			if(ss >= 1) {
				ss = ss - 1;
				$('.Ajax_Out').text(ss);
			} else {
				clearInterval(picInt);
				try {
					$window.parent.location.href = data.returnData;
					$window.location.href = data.returnData;
				} catch(e) {
					log('timeout!');
				}
			}
		}, 1000);
		return false;
	}
}

app.config(function($httpProvider) {
	$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

	$httpProvider.defaults.transformRequest = [function(data) {
		/**
		 * The workhorse; converts an object to x-www-form-urlencoded serialization.
		 * @param {Object} obj
		 * @return {String}
		 */
		var param = function(obj) {
			var query = '';
			var name, value, fullSubName, subName, subValue, innerObj, i;
			for(name in obj) {
				value = obj[name];
				if(value instanceof Array) {
					for(i = 0; i < value.length; ++i) {
						subValue = value[i];
						fullSubName = name + '[' + i + ']';
						innerObj = {};
						innerObj[fullSubName] = subValue;
						query += param(innerObj) + '&';
					}
				} else if(value instanceof Object) {
					for(subName in value) {
						subValue = value[subName];
						fullSubName = name + '[' + subName + ']';
						innerObj = {};
						innerObj[fullSubName] = subValue;
						query += param(innerObj) + '&';
					}
				} else if(value !== undefined && value !== null) {
					query += encodeURIComponent(name) + '=' +
						encodeURIComponent(value) + '&';
				}
			}
			return query.length ? query.substr(0, query.length - 1) : query;
		};
		return angular.isObject(data) && String(data) !== '[object File]' ?	param(data) : data;
	}];
});

var editExaDataLayer = null;
var ruleSelectType = 0;
$('.editExaDataBtn').live('click', function() {
    var editExaDataLayer = $.layer({
        type: 1,
        title: false,
        area: ['700', 'auto'],
        border: [0], //去掉默认边框
        shade: [0.3, '#000'], //去掉遮罩
        closeBtn: [0, false], //去掉默认关闭按钮
        fadeIn: 500,
        move: "#editExaData_tile",
        page: {
            dom: '#editExaDataLayer'
        }
    });
    //自设关闭
    $('#editExaDataLayer > .closeBtn,#editExaDataLayer .cancelLayer,#editExaSubmitBtn').live('click', function() {
        layer.close(editExaDataLayer);
    });
});
var edit = {
    "qCompanyList": function(_this, weiboArr, jsons) {
        var _obj = $("#CustomsAreaList");
        var params = {
    		pageIndex : 1,
    		pageSize : 1000000
        }
        $.ajax({
            type: "POST",
            url: basePath + "Tagvalue/queryTagvalue.do?pageIndex="+params.pageIndex+"&pageSize="+params.pageSize,
            data: params,
            success: function(data) {
                if(data.returnCode == 10000) {
                    var s2 = data.returnData.length;
                    if(s2 > 0) {
                        var htmls = "";
                        var checkedHtmls = "";
                        for(var i = 0; i < s2; i++) {
                            var checkedBtn = "";
                            var checked = "";
                            var tagvalue_id = data.returnData[i].tagvalue_id;
                            var checkeddefault = "";
                            var num = weiboArr.length;
                            var tf = null;
                            for(var nn = 0; nn < num; nn++) {
                                if(tagvalue_id == weiboArr[nn]) {
                                    checkedBtn = "true";
                                    checked = "checked";
                                    checkeddefault = "true";
                                    tf = true;
                                    break;
                                } else {
                                    checkedBtn = "false";
                                    checkeddefault = "false";
                                    checked = "";
                                    tf = false;
                                }
                            }
                            if(tf == true) {
                                checkedHtmls += "<div class='infoLlist' title='" + data.returnData[i].tag_value + "'><span class='ui_checkbox " + checked + "' tagv-id= '" + data.returnData[i].tagvalue_id + "' checkedBtn='" + checkedBtn + "' checkeddefault='" + checkeddefault + "'></span> <font>" + data.returnData[i].tag_type +"-"+ data.returnData[i].tag_value + "</font></div>";
                            } else if(tf == false) {
                                htmls += "<div class='infoLlist' title='" + data.returnData[i].tag_value + "'><span class='ui_checkbox " + checked + "' tagv-id= '" + data.returnData[i].tagvalue_id + "' checkedBtn='" + checkedBtn + "' checkeddefault='" + checkeddefault + "'></span> <font>" + data.returnData[i].tag_type +"-"+ data.returnData[i].tag_value + "</font></div>";
                            }
                        }
                        _obj.html(checkedHtmls + htmls + "<div class='clear'></div>");
                        checkTrueFalse();
                    }
                    if(s2 < 1) {
                        _obj.html("<br><bR><p align='center'>很遗憾，没有查询到相关的数据！</p><br><bR>");
                    }
                } else if(data.returnCode == 999994) {
                    setUserTimeout(data);
                } else {
                    layer.msg(data.returnMessage, 2, -1);
                }
            },
            error: function(message) {
                ayer.msg("操作失败，请重试！", 2, -1);
            },
            beforeSend: function() {
                var imgGif = "<p class='loadingGif'></p>";
                _obj.html(imgGif);
            }
        });
    },
    "quyeryCheck": function(ids, names) {
        var $selectShowSpan = $(".editExaDataBtn");
        var $showSpan = $selectShowSpan.parent().prev("span");
        $selectShowSpan.attr({
            ids: ids
        });
        $showSpan.attr({
            ids: ids
        });
        $showSpan.text(names);
    }
}
$(".infoLlist .ui_checkbox").live("click", function() {
    if($(this).attr("checkedBtn") == "true") {
        $(this).attr("checkedBtn", "false");
        $(this).removeClass("checked");
    } else {
        $(this).attr("checkedBtn", "true");
        $(this).addClass("checked");
    }
});
$(".editExaDataBtn").live("mouseover", function() {
	var strId = $(this).attr('ids');
	var weiboArr = strId.split(",");
	ruleSelectType = $(this).attr('type');
	var params = {
        relation_type: ruleSelectType
    };
    edit.qCompanyList($(this), weiboArr, params);
});

$("#tagvalueQueryBtn").live("click", function() {
	publicQDataList3($("#tagvName"));
});
$('.enterKeyDownElement2').keydown(function(e) {
	if(e.keyCode == 13) {
		publicQDataList3($("#tagvName"));
	}
});

function publicQDataList3(_this) {
	var kV = $.trim(_this.val());
	$("#CustomsAreaList .infoLlist").each(function() {
			var name = $(this).children("font").text();
			var isOf = $.trim(name.indexOf(kV));
        if(isOf > -1) {
            $(this).show();
        } else {
            $(this).hide();
        }
    });
}                
$("#editExaSubmitBtn").live("click", function() {
    var trueArr = new Array();
    var trueStrArr = new Array();
    $("#CustomsAreaList .ui_checkbox").each(function() {
        var id = $(this).attr("tagv-id");
        var name = $(this).next("font").text();
        var checkedbtn = $(this).attr("checkedbtn");
        var checkeddefault = $(this).attr("checkeddefault");
        if(checkedbtn == "true") {
            trueArr.push(id);
            trueStrArr.push(name);
        };
    });
    var trueArrs = "";
    var trueStrArrs = "";
    if(trueArr.length > 0) {
        trueArrs = trueArr.join(",");
        trueStrArrs = trueStrArr.join(",");
    }
    edit.quyeryCheck(trueArrs, trueStrArrs);
    $(".xubox_main").css("cssText", "height:45px!important; z-index:198916;");
});

$(".selectAllAreaGoGo .allSel").live("click", function() {
    var checkedbtn = $(this).attr("checkedbtn");
    if(checkedbtn == "true") {
        $("#CustomsAreaList .infoLlist .ui_checkbox").addClass("checked").attr("checkedbtn", "true");
    } else {
        $("#CustomsAreaList .infoLlist .ui_checkbox").removeClass("checked").attr("checkedbtn", "false");
    }
});

$(".selectAllAreaGoGo .reDefault").live("click", function() {
    $("#CustomsAreaList .infoLlist .ui_checkbox").each(function() {
        var checkeddefault = $(this).attr("checkeddefault");
        if(checkeddefault == "true") {
            $(this).addClass("checked").attr("checkedbtn", "true");
        } else {
            $(this).removeClass("checked").attr("checkedbtn", "false");
        }
    });
    checkTrueFalse();
});
$("#CustomsAreaList .infoLlist .ui_checkbox").live("click", function() {
    checkTrueFalse();
});

function checkTrueFalse() {
    var isTrue = "true";
    $("#CustomsAreaList .infoLlist .ui_checkbox").each(function() {
        var checkedbtn = $(this).attr("checkedbtn");
        if(checkedbtn == "false") {
            isTrue = "false";
            return;
        }
    });
    if(isTrue == "false") {
        $(".selectAllAreaGoGo .allSel").removeClass("checked").attr("checkedbtn", "false");
    } else {
        $(".selectAllAreaGoGo .allSel").addClass("checked").attr("checkedbtn", "true");
    }
}

app.directive('ngFocus', [function() {
	 var FOCUS_CLASS = "ng-focused";
	 return {
	    restrict: 'A',
	    require: 'ngModel',
	    link: function(scope, element, attrs, ctrl) {
	    	ctrl.$focused = false;
	    	element.bind('focus', function(evt) {
		        element.addClass(FOCUS_CLASS);
		        scope.$apply(function() {ctrl.$focused = true;});
		    }).bind('blur', function(evt) {
		      	console.log(ctrl.$error.required)
		        element.removeClass(FOCUS_CLASS);
		        scope.$apply(function() {ctrl.$focused = false;});
		    });
	    }
	 }
}]);
//新增
app.controller('addCtrl', function($scope, $http, $window, $timeout) {
	var vm = $scope.vm = content =$scope.content= {
		weixinuser_Id: null,
		weixin_name: null,
		tagvalue_id : null,
		//"weixin_id" : weixin_id
	};
	//点击取消关闭窗口
	$scope.close = function(e){
		window.parent.layer.closeAll();
	}
	var avoidDup = true;
	$scope.domAjax = function(e){
		var ids = $(".editExaDataBtn").attr('ids');
		var params = {
				weixinuser_Id : $scope.vm.weixinuser_Id,
				weixin_name : $scope.vm.weixin_name,
				tagvalue_id : ids,
				weixin_id : weixin_id
		}
		
		if(e == "save"){
			if(avoidDup==false){
				return false;
			}
			//取页面值，判断长度是否合法
			var urls = "weixin/addWeixin.do";
			/*var weixinuser_Id = $("#weixinuser_Id").val();
			var weixin_name = $("#weixin_name").val();
			if(weixinuser_Id.length>10||weixin_name.length>10){
				layer.msg("参数长度为100，请重新填写",2,-1);
				return false;
			}*/
			if(vm.weixinuser_Id!=null&&vm.weixin_name!=null){
				avoidDup = false;
				$.ajax({
					type : "post",
					url : basePath+urls,
					data : params,
					error: function(request){
						layes.msg("操作失败，请重试",2,-1);
					},
					success:function(data){
						var j = timeout_json(data,$window);
						if(j == false){
							return false;
						}
						if(data.returnCode == 10000){
							layer.msg(data.returnMessage,1,10);
							$timeout(function(){
								var index = parent.layer.getFrameIndex(window.name);
								try{
									window.parent.$('#Msearch').trigger('click');
								}catch(e){}
								parent.layer.close(index);
							},1000);
						}else{
							layer.msg(data.returnMessage,2,-1);
							avoidDup = true;
							return false;
						}
					}
				});
			}
		}	
	}
});
